﻿using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using TimeTable.Domain.DataAccess;

namespace TimeTable
{
    public partial class EditorForm : Form
    {
        public EditorForm()
        {
            InitializeComponent();
        }

        private string GetActiveTableName()
        {
            var tableName = "";

            if (divisionsRadioButton.Checked) tableName = "Divisions";
            else if (studyUnitsRadioButton.Checked) tableName = "StudyUnits";
            else if (teachersRadioButton.Checked) tableName = "Teachers";
            else if (roomsRadioButton.Checked) tableName = "Rooms";
            else if (timeTablesRadioButton.Checked) tableName = "TimeTables";
            else if (timeTableUnitsRadioButton.Checked) tableName = "TimeTableUnits";

            return tableName;
        }

        private void OpenClick(object sender, System.EventArgs e)
        {
            var tableName = GetActiveTableName();

            bindingSource.DataSource = DataAccessConnection.Instance.OpenTable(tableName);
            tableView.DataSource = bindingSource;

            navigator.Enabled = true;
            open.Enabled = false;
            save.Enabled = true;
            create.Enabled = false;
            drop.Enabled = false;
            tablesBox.Enabled = false;
        }

        private void SaveClick(object sender, System.EventArgs e)
        {
            var tableName = GetActiveTableName();

            DataAccessConnection.Instance.SaveTable(tableName, bindingSource.DataSource as DataTable);

            tableView.DataSource = null;
            bindingSource.DataSource = null;

            MessageBox.Show("Commited successfully!");

            open.Enabled = true;
            save.Enabled = false;
            create.Enabled = true;
            drop.Enabled = true;
            tablesBox.Enabled = true;
        }

        private void CreateClick(object sender, System.EventArgs e)
        {
            if (DataAccessConnection.Instance.InitializeDataBase())
            {
                MessageBox.Show("Tables created successfully!");
            }
            else
            {
                MessageBox.Show("Tables already created!");
            }
        }

        private void DropClick(object sender, System.EventArgs e)
        {
            if (DataAccessConnection.Instance.DropTables())
            {
                MessageBox.Show("Tables droped successfully!");
            }
            else
            {
                MessageBox.Show("Tables already droped!");
            }
        }
    }
}
